package mainService.services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import mainService.data.HttpMessageWriter;
import mainService.data.IGeneratorXml;
import mainService.data.MimeHTTP;
import mainService.data.XMLGenerator;
import databaseManager.connection.ConnectionManager;
import databaseManager.connection.IConnection;

/**
 * Classe padre di tutti i servizi di lettura del db.
 * 
 * @author Mattia, Daniel
 * 
 */
public class ReadingServices {

	private ArrayList<String> valoriCampi = new ArrayList<String>();

	/**
	 * restituisce la risposta XML
	 * 
	 * @param query
	 * @param campiXML nomi tag nel XML
	 * @return
	 */
	public ArrayList<String> getResult(String qry, ArrayList<String> campiXML) {

		HttpMessageWriter writer = new HttpMessageWriter(MimeHTTP.XML);
		ArrayList<String> risposta = writer.createHttpMessageHeader();

		IGeneratorXml generatorXML = new XMLGenerator(risposta, campiXML);

		// gestione del db
		IConnection manager = new ConnectionManager();
		manager.connect();
		Connection conn = manager.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery(qry);

			while (rs.next()) {
				for (int i = 0; i < campiXML.size(); i++) {

					valoriCampi.add(rs.getString(campiXML.get(i)));
				}

				generatorXML.addElement(valoriCampi);
				valoriCampi.clear();
			}

		} catch (SQLException e) {

			e.printStackTrace();
		}
		return generatorXML.getRisposta();
	}

}
